<template>
  <div class="collision-check">
    <el-table :data="collisionCheckList" style="width: 100%" v-loading="loading">
      <el-table-column prop="checkName" label="检测名称" width="150" />
      <el-table-column prop="checkType" label="检测类型" width="120">
        <template #default="{ row }">
          <el-tag :type="getCheckTypeTag(row.checkType)">
            {{ getCheckTypeText(row.checkType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="checkPeriod" label="检测周期(天)" width="100" />
      <el-table-column prop="checkRules" label="检测规则" min-width="200">
        <template #default="{ row }">
          <div v-if="row.checkRules.phone">手机: {{ row.checkRules.phone.enabled ? '启用' : '禁用' }}</div>
          <div v-if="row.checkRules.idCard">身份证: {{ row.checkRules.idCard.enabled ? '启用' : '禁用' }}</div>
          <div v-if="row.checkRules.email">邮箱: {{ row.checkRules.email.enabled ? '启用' : '禁用' }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="80">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">
            {{ row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="描述" min-width="150" show-overflow-tooltip />
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
          <el-button 
            :type="row.status === 1 ? 'danger' : 'success'" 
            link 
            @click="handleToggleStatus(row)"
          >
            {{ row.status === 1 ? '禁用' : '启用' }}
          </el-button>
          <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="pageInfo.pageNum"
      v-model:page-size="pageInfo.pageSize"
      :page-sizes="[10, 20, 50, 100]"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 新增/编辑撞库检测对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="checkFormRef"
        :model="checkForm"
        :rules="checkRules"
        label-width="100px"
      >
        <el-form-item label="检测名称" prop="checkName">
          <el-input v-model="checkForm.checkName" placeholder="请输入检测名称" />
        </el-form-item>
        <el-form-item label="检测类型" prop="checkType">
          <el-select v-model="checkForm.checkType" placeholder="请选择检测类型" style="width: 100%">
            <el-option label="手机号" value="PHONE" />
            <el-option label="身份证" value="ID_CARD" />
            <el-option label="邮箱" value="EMAIL" />
            <el-option label="自定义" value="CUSTOM" />
          </el-select>
        </el-form-item>
        <el-form-item label="检测周期" prop="checkPeriod">
          <el-input-number v-model="checkForm.checkPeriod" :min="1" :max="365" placeholder="请输入检测周期(天)" />
        </el-form-item>
        <el-form-item label="检测规则" prop="checkRules">
          <div class="check-rules">
            <el-checkbox v-model="checkForm.checkRules.phone.enabled">手机号检测</el-checkbox>
            <el-checkbox v-model="checkForm.checkRules.idCard.enabled">身份证检测</el-checkbox>
            <el-checkbox v-model="checkForm.checkRules.email.enabled">邮箱检测</el-checkbox>
          </div>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="checkForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="checkForm.description" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入检测描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { getCollisionCheckList, createCollisionCheck, updateCollisionCheck, deleteCollisionCheck, updateCollisionCheckStatus } from '@/api/engine'
import type { CollisionCheckConfig } from '@/types/api'

const loading = ref(false)
const collisionCheckList = ref<CollisionCheckConfig[]>([])
const total = ref(0)

const pageInfo = reactive({
  pageNum: 1,
  pageSize: 10
})

const dialogVisible = ref(false)
const submitLoading = ref(false)
const checkFormRef = ref<FormInstance>()

const checkForm = reactive({
  id: undefined as number | undefined,
  checkName: '',
  checkType: 'PHONE' as 'PHONE' | 'ID_CARD' | 'EMAIL' | 'CUSTOM',
  checkPeriod: 30,
  checkRules: {
    phone: { enabled: true },
    idCard: { enabled: false },
    email: { enabled: false }
  },
  status: 1,
  description: ''
})

const checkRules: FormRules = {
  checkName: [{ required: true, message: '请输入检测名称', trigger: 'blur' }],
  checkType: [{ required: true, message: '请选择检测类型', trigger: 'change' }],
  checkPeriod: [{ required: true, message: '请输入检测周期', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

const dialogTitle = computed(() => 
  checkForm.id ? '编辑撞库检测' : '新增撞库检测'
)

const getCheckTypeTag = (type: string) => {
  const tagMap: Record<string, string> = {
    'PHONE': 'primary',
    'ID_CARD': 'success',
    'EMAIL': 'warning',
    'CUSTOM': 'info'
  }
  return tagMap[type] || 'info'
}

const getCheckTypeText = (type: string) => {
  const textMap: Record<string, string> = {
    'PHONE': '手机号',
    'ID_CARD': '身份证',
    'EMAIL': '邮箱',
    'CUSTOM': '自定义'
  }
  return textMap[type] || type
}

const fetchCollisionCheckList = async () => {
  loading.value = true
  try {
    const response = await getCollisionCheckList(pageInfo)
    collisionCheckList.value = response.records
    total.value = response.total
  } catch (error) {
    ElMessage.error('获取撞库检测列表失败')
  } finally {
    loading.value = false
  }
}

const handleAdd = () => {
  checkForm.id = undefined
  checkForm.checkName = ''
  checkForm.checkType = 'PHONE' as 'PHONE' | 'ID_CARD' | 'EMAIL' | 'CUSTOM'
  checkForm.checkPeriod = 30
  checkForm.checkRules = {
    phone: { enabled: true },
    idCard: { enabled: false },
    email: { enabled: false }
  }
  checkForm.status = 1
  checkForm.description = ''
  dialogVisible.value = true
}

const handleEdit = (row: CollisionCheckConfig) => {
  checkForm.id = row.id
  checkForm.checkName = row.checkName
  checkForm.checkType = row.checkType as 'PHONE' | 'ID_CARD' | 'EMAIL' | 'CUSTOM'
  checkForm.checkPeriod = row.checkPeriod
  checkForm.checkRules = {
    phone: { enabled: false },
    idCard: { enabled: false },
    email: { enabled: false },
    ...row.checkRules
  }
  checkForm.status = row.status
  checkForm.description = row.description || ''
  dialogVisible.value = true
}

const handleToggleStatus = async (row: CollisionCheckConfig) => {
  try {
    await ElMessageBox.confirm(
      `确定要${row.status === 1 ? '禁用' : '启用'}检测"${row.checkName}"吗？`,
      '提示',
      { type: 'warning' }
    )
    
    await updateCollisionCheckStatus(row.id, row.status === 1 ? 0 : 1)
    ElMessage.success(`${row.status === 1 ? '禁用' : '启用'}成功`)
    fetchCollisionCheckList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

const handleDelete = async (row: CollisionCheckConfig) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除检测"${row.checkName}"吗？`,
      '提示',
      { type: 'warning' }
    )
    
    await deleteCollisionCheck(row.id)
    ElMessage.success('删除成功')
    fetchCollisionCheckList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleSubmit = async () => {
  if (!checkFormRef.value) return
  
  try {
    await checkFormRef.value.validate()
    submitLoading.value = true
    
    if (checkForm.id) {
      await updateCollisionCheck(checkForm.id, checkForm)
      ElMessage.success('更新成功')
    } else {
      await createCollisionCheck(checkForm)
      ElMessage.success('创建成功')
    }
    
    dialogVisible.value = false
    fetchCollisionCheckList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  } finally {
    submitLoading.value = false
  }
}

const handleDialogClose = () => {
  checkFormRef.value?.resetFields()
}

const handleSizeChange = (val: number) => {
  pageInfo.pageSize = val
  fetchCollisionCheckList()
}

const handleCurrentChange = (val: number) => {
  pageInfo.pageNum = val
  fetchCollisionCheckList()
}

onMounted(() => {
  fetchCollisionCheckList()
})
</script>

<style scoped>
.collision-check {
  padding: 20px;
}

.check-rules {
  display: flex;
  flex-direction: column;
  gap: 10px;
}
</style>